package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Transactional

    public void submit(Orders orders){
        //获取当前用户ID
        Long currentId = BaseContext.GetCurrentId();

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart>queryWrapper= new LambdaQueryWrapper<>();


        queryWrapper.eq(ShoppingCart::getUserId,currentId);

        //进行判断，拍品价格是否改变，版本号控制方式检测
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
        if(shoppingCartList == null || shoppingCartList.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }
        log.info("开始了");
        shoppingCartList.forEach(item1 -> {
            //版本号cas
            AtomicInteger number1 = new AtomicInteger(item1.getDnumber().intValue());
            //log.info(String.valueOf(number));
            //LocalDateTime createTime = item1.getCreateTime();
            Long dishId = item1.getDishId();
            Dish byId = dishService.getById(dishId);
            AtomicInteger number = new AtomicInteger(byId.getNumber().intValue());
            //LocalDateTime updateTime = byId.getUpdateTime();
            if(!(number.get() == number1.get())){
                System.out.println("         拍品价格已经更新");
                log.info(String.valueOf(number));
                log.info(byId.getNumber().toString());

                throw new CustomException("拍品价格已经更新");
            }
           // System.out.println(createTime);
          //  System.out.println("     ");
           // System.out.println(updateTime);
            // 表示价格已经更新，抛出异常
          /*  if (createTime.isBefore(updateTime)) {
                System.out.println("         拍品价格已经更新");
                Set keys = redisTemplate.keys("dish_*");
                redisTemplate.delete(keys);
                throw new CustomException("拍品价格已经更新");

            }*/


            //查询用户信息
            User user = userService.getById(currentId);
            //查询地址信息
            Long addressBookId = orders.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
            if(addressBook == null){
                throw new CustomException("地址信息为空，不能下单");
            }



            long orderId = IdWorker.getId();//订单号
            //原子整数类，保证线程安全
            AtomicInteger amount = new AtomicInteger(0);

            List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderId);
                orderDetail.setNumber(item.getNumber());
                orderDetail.setDishFlavor(item.getDishFlavor());
                orderDetail.setDishId(item.getDishId());
                orderDetail.setSetmealId(item.getSetmealId());
                orderDetail.setName(item.getName());
                orderDetail.setImage(item.getImage());
                orderDetail.setAmount(item.getAmount());
                amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
                return orderDetail;
            }).collect(Collectors.toList());

            orders.setId(orderId);

            orders.setOrderTime(LocalDateTime.now());
            orders.setCheckoutTime(LocalDateTime.now());
            orders.setStatus(2);
            orders.setAmount(new BigDecimal(amount.get()));//总金额
            orders.setUserId(currentId);
            orders.setNumber(String.valueOf(orderId));
            String userName = user.getName();
            if(userName == null){
                userName = user.getPhone();
            }
            orders.setUserName(userName);
            orders.setConsignee(addressBook.getConsignee());
            orders.setPhone(addressBook.getPhone());
            orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                    + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                    + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                    + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

            Dish temp = dishService.getById(dishId);
            AtomicInteger number3 = new AtomicInteger(temp.getNumber().intValue());
            if(!(number1.get() == number3.get())){
                System.out.println("         拍品价格已经更新");
                log.info(String.valueOf(number));
                log.info(byId.getNumber().toString());

                throw new CustomException("拍品价格已经更新");
            }
            //向订单插入数据，一条数据
            this.save(orders);

            //向订单细表插入数据，多条数据
            orderDetailService.saveBatch(orderDetails);

            orderDetails.stream().forEach((item2)->{
                Long dishId1 = item2.getDishId();
                Dish byId1 = dishService.getById(dishId1);
                byId1.setNumber(byId1.getNumber().add(BigDecimal.valueOf(1)));
                byId1.setPrice(item2.getAmount().multiply(BigDecimal.valueOf(item2.getNumber()*100)));
                dishService.saveOrUpdate(byId1);

            });


        });
    //清空购物车
        shoppingCartService.remove(queryWrapper);
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        log.info("结束了");






    }

}
